package com.liao.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.liao.seckill.constant.GoodsConstant;
import com.liao.seckill.constant.OrderConstant;
import com.liao.seckill.dao.GoodsMiaoShaDao;
import com.liao.seckill.dao.MiaoShaOrderDao;
import com.liao.seckill.dao.OrderDao;
import com.liao.seckill.exception.GoodsStockException;
import com.liao.seckill.pojo.*;
import com.liao.seckill.service.GoodsMiaoshaService;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class GoodsMiaoShaServiceImpl implements GoodsMiaoshaService {

    private final GoodsMiaoShaDao goodsMiaoShaDao;
    private final StringRedisTemplate redisTemplate;

    public GoodsMiaoShaServiceImpl(GoodsMiaoShaDao goodsMiaoShaDao, StringRedisTemplate redisTemplate) {
        this.goodsMiaoShaDao = goodsMiaoShaDao;
        this.redisTemplate = redisTemplate;
    }

    /**
     * 使用redis缓存数据可以使吞吐量达到6000+，不使用只有1500左右,直接return null有8000左右
     *
     */
    @Override
    public List<TbGoodsMiaoshaAndGoods> findMiaoshaGoods() {
        String  strTbGoodsMiaoshaAndGoods= redisTemplate.opsForValue().get(GoodsConstant.GOODS_MIAOSHA_CACHE_KEY + ":" + GoodsConstant.GOODS_MIAOSHA_CACHE_DETAIL_KEY);
        if (strTbGoodsMiaoshaAndGoods != null){
            return JSON.parseObject(strTbGoodsMiaoshaAndGoods, List.class);
        }
        List<TbGoodsMiaoshaAndGoods> tbGoodsMiaoshaAndGoods = goodsMiaoShaDao.findTbGoodsMiaoshaAndGoods();
        if (tbGoodsMiaoshaAndGoods != null) {
            String s = JSON.toJSONString(tbGoodsMiaoshaAndGoods);
            redisTemplate.opsForValue().set(GoodsConstant.GOODS_MIAOSHA_CACHE_KEY + ":" + GoodsConstant.GOODS_MIAOSHA_CACHE_DETAIL_KEY,
                    s, GoodsConstant.GOODS_MIAOSHA_CACHE_EXPIRE_TIME_DEFAULT, TimeUnit.SECONDS);
        }
        return tbGoodsMiaoshaAndGoods;
    }

    @Override
    public TbGoodsMiaosha findById(Integer id) {
        Optional<TbGoodsMiaosha> tbGoodsMiaosha = goodsMiaoShaDao.findById(id);
        if (tbGoodsMiaosha.isEmpty()){
            return null;
        }
        return tbGoodsMiaosha.get();
    }
}
